<template>
  <h1>table-plan 组件</h1>
  <div class="bg-light-1" style="height: calc(100vh - 80px)">
    <f-table-plan ref="tablePlanRef" v-bind="gridOptions" v-on="gridEvents">
      <template #toolbar_right>
        <f-button danger class="mr10">删除</f-button>
        <f-button class="mr10" @click="handleOpenTree">次要</f-button>
        <f-button type="primary" class="mr10" @click="handleOpenEdit('add')">新增</f-button>
      </template>
      <template #edit_content="{ row }">
        <f-input v-model:value="row.name" />
      </template>
      <template #edit_content_money="{ row }">
        <f-input v-model:value="row.price" />
      </template>
      <template #top>
        Top
        <f-button @click="handleSearch">查询</f-button>
        <f-button @click="handleClick">合并单元格</f-button>
        <f-button @click="handleAddRow">新增行</f-button>
        <f-button @click="handFormsData">获取forms数据</f-button>
        <f-button @click="handFormsReset">重置forms数据</f-button>
        <f-button @click="updateModel">修改model数据</f-button>
      </template>
      <!-- <template #bottom>
        <div class="lh32" :class="{ 'h300': openExpand }" @click="handleRetract">我是bottom</div>
      </template> -->
    </f-table-plan>
  </div>
</template>

<script lang="ts" setup>
import { h, reactive, ref, computed, watch } from 'vue';
import { set, get } from '@vueuse/core';
import { useTrendsComp } from '../../packages/index';
import * as edit from './forms.vue';
import * as forms from './forms.vue';
import * as tree from './tree.vue';

const tablePlanRef = ref();
const openExpand = ref(false);
const dataTreeSelectValue = ref([]);
console.log(tablePlanRef);
const updateModel = () => {
  tablePlanRef.value.formData.name = '12312312';
  tablePlanRef.value.formData.sex = 1;
};
// 收起事件
const handleRetract = () => {
  set(openExpand, !openExpand.value);
  console.log('handleRetract');
  const $grid = get(tablePlanRef);
  if ($grid) {
    $grid.updateData();
  }
};

const handleClick = () => {
  // console.log('handleClick', row);
  const $grid = get(tablePlanRef);
  const cells = [{ row: 0, col: 1, rowspan: 4, colspan: 1 }];
  if ($grid) {
    // console.log('grid', $grid);
    // console.log('handleClick:getData', $grid.getData());
    // console.log('handleClick:setCurrentRow', $grid.setCurrentRow(row.row));
    $grid.setMergeCells(cells);
  }
  // set(mergeCells, cells);
};
const handFormsData = () => {
  const $grid = get(tablePlanRef);
  if ($grid) {
    console.log('handFormsData:getData', $grid.getFormsData());
  }
};

const handFormsReset = () => {
  const $grid = get(tablePlanRef);
  if ($grid) {
    console.log('handFormsReset:grid', $grid);
    $grid.forms.resetFields();
    // $grid.forms.refreshForms();
  }
};

const handleSearch = () => {
  // gridOptions.loading = true;
  // apiServe({ page: 1, size: 20 }).then((res: any) => {
  //   setTimeout(() => {
  //     const $grid = get(tablePlanRef);
  //     if ($grid) {
  //       $grid.loadData(res.data);
  //     }
  //     gridOptions.loading = false;
  //   }, 1000 * 2);
  // });
  const $grid = get(tablePlanRef);
  if ($grid) {
    $grid.refresh();
  }
};

const handleAddRow = () => {
  const $grid = get(tablePlanRef);
  if ($grid) {
    // console.log('handleInsert', $grid);
    const rowNew = {
      code: $grid.getTableData().tableData.length + 1,
      name: '草稿'
    };
    $grid.insertAt(rowNew, -1);
    const row = $grid.getRecordset().insertRecords[$grid.getRecordset().insertRecords.length - 1];
    // console.log(row);
    $grid.setEditRow(row, 'name');
  }
};

const apiServe = (data) =>
  new Promise((resolve, reject) => {
    fetch(`/base/products/queryInstPage`, {
      method: 'post',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
        Accesstoken: window['FokUIOptions'].token()
      }
    })
      .then((response) => response.json())
      .then((res) => resolve(res))
      .catch(() => reject());
  });

// const list = ref({})
// const listB = reactive({
//   list: []
// })
// listB.list = list;

const gridOptions = reactive({
  stripe: false,
  loading: false,
  // columnConfig: {
  //   resizable: true
  // },
  toolbarConfig: {
    // search: true,
    title: '我是标题'
  },
  rowConfig: {
    keyField: 'productId',
    isCurrent: true
  },
  // checkboxConfig: {
  //   reserve: true
  // },
  fitConfig: {
    enabled: true,
    title: '我是子区域标题',
    component: forms
  },
  showFooter: true,
  footerData: [{ name: 'footer' }],
  showMore: false,
  mergeFooterItems: [{ row: 0, col: 2, colspan: 15, rowspan: 1 }],
  forms: [
    {
      type: 'date-range',
      field: 'beginDate',
      title: '领药时间',
      show: () => true,
      params: {
        placeholder: ['开始时间', '结束时间'],
        showTime: { format: 'HH:mm' },
        format: 'YYYY-MM-DD HH:mm',
        valueFormat: 'YYYY-MM-DD HH:mm',
        isDefault: true,
        type: 'select',
        isAutoFill: true
      }
    },
    { field: 'name', label: '名称', value: '123' },
    {
      type: 'select',
      field: 'bba',
      label: '下拉选项A',
      props: { options: [] }
    },
    {
      type: 'tree-select',
      field: 'institutionId',
      label: '机构',
      props: {
        treeData: [],
        treeNodeFilterProp: 'name',
        fieldNames: { children: 'children', label: 'name', value: 'id' },
        allowClear: true
      }
    },
    { type: 'input-number', field: 'age', label: '年龄' },
    { type: 'date-picker', field: 'data', label: '日期' },
    {
      type: 'select',
      field: 'sex',
      label: '性别',
      props: { options: [{ value: 1, label: '男' }], class: 's-w80' }
    },
    {
      type: 'dictionary',
      field: 'dictionary',
      label: '字典',
      props: { code: 'VisitType' }
    }
  ],
  query: (page, form) =>
    Promise.resolve({
      data: new Array(200).fill(0).map((item) => ({})),
      pageInfo: {
        total: 200,
        size: 20
      }
    }),
  columns: [
    { type: 'checkbox', width: 40 },
    { type: 'seq', title: '序', width: 50 },
    {
      field: 'name',
      title: '医师',
      slots: {
        edit: 'edit_content',
        footer: () =>
          h(
            'div',
            'footer Ddata kdfjasdljflsdajf ,.jfdsfsadfasfd 092384092384092384023840238482304 KLJ到了咖啡机阿拉善打卡机发啦受打击发撒代发'
          )
      }
    },
    { type: 'link', field: 'code', title: '医院:link' },
    {
      type: 'status',
      field: 'doseType.code',
      title: '岗位:status',
      params: [
        { value: 'Develop', label: 'Develop:开发' },
        { value: 'Test', label: 'Test:测试' },
        { value: 'PM', label: 'PM:产品' },
        { value: 'Designer', label: 'Designer:设计' }
      ]
    },
    { type: 'image', field: 'minPackUnit', title: 'image', width: 80 },
    {
      type: 'money',
      field: 'price',
      title: 'money',
      slots: { edit: 'edit_content_money' }
    },
    { type: 'status', field: 'isShows', title: 'status' },
    {
      type: 'switch',
      field: 'isBase',
      title: 'switch',
      params: {
        unCheckedChildren: 'A',
        checkedChildren: 'B',
        // disabled: (row) => row.isBase,
        events: {
          change: (checked, row) => {
            console.log('change', checked, row);
            // return Promise.resolve();
            return new Promise((resolve) => {
              setTimeout(() => {
                resolve(true);
              }, 1000 * 0.6);
            });
          }
        }
      }
    },
    { type: 'switch', field: 'isFeeItem', title: 'switch' },
    {
      type: 'operate',
      title: '操作',
      params: [
        {
          label: '详情',
          // popconfirmTitle: "详情确认？",
          disabled: (row) => row.isBase,
          click: (row) => {
            console.log('详情', row);
            handleOpenTree();
          }
        },
        {
          label: '编辑',
          show: (row) => row.isFeeItem,
          click: (row) => {
            const $grid = get(tablePlanRef);
            if ($grid) {
              console.log('编辑', row);
              $grid.setEditRow(row, 'name');
            }
          }
        },
        {
          label: '删除',
          popconfirmTitle: '你确认要删除当前数据吗？',
          show: (row) => row.isFeeItem,
          // disabled: (row) => false,
          // power: "c",
          click: (row) => {
            console.log('删除', row);
          }
        },
        {
          label: '操作1',
          popconfirmTitle: 'AAAAAAAAA',
          show: (row) => row.isFeeItem
        },
        {
          label: '操作操作2',
          click: (row) => {
            handleOpenEdit('edit', row);
          }
        },
        { label: '操作操作操作3', popconfirmTitle: 'CCCCCCCCCCCCCC' },
        { label: '操作操作操作操作4', popconfirmTitle: 'DDDDDDDDDDDDDDD' }
      ]
    }
  ]
  // data: [
  //   {
  //     id: 10001,
  //     name: 'Test1',
  //     code: 'T1',
  //     price: 323429.3,
  //     doseType: { code: 'Develop' },
  //     isShows: true,
  //     minPackUnit: 'productImg/2c93001ab36912625521777dce3c2c63.png'
  //   },
  //   { id: 10002, name: 'Test2', code: 'T2', price: 33.5, doseType: { code: 'Test' }, isShows: true, minPackUnit: 'Women' },
  //   { id: 10003, name: 'Test3', code: 'T3', price: 0, doseType: { code: 'PM' }, isShows: false, minPackUnit: 'Man' },
  //   {
  //     id: 10004,
  //     name: 'Test4',
  //     code: 'T4',
  //     price: 23000.55667,
  //     doseType: { code: 'Designer' },
  //     isShows: true,
  //     minPackUnit: 'Women'
  //   },
  //   { id: 10005, name: 'Test5', code: 'T5', price: 387, doseType: { code: 'Develop' }, isShows: false, minPackUnit: 'Women' },
  //   {
  //     id: 10006,
  //     name: 'Test6',
  //     code: 'T6',
  //     price: 98400.024354,
  //     doseType: { code: 'Designer' },
  //     isShows: false,
  //     minPackUnit: 'Women'
  //   },
  //   { id: 10007, name: 'Test7', code: 'T7', price: 282799000003, doseType: { code: 'Test' }, isShows: true, minPackUnit: 'Man' },
  //   { id: 10008, name: 'Test8', code: 'T8', price: null, doseType: { code: 'Develop' }, isShows: true, minPackUnit: 'Man' }
  // ]
});

setTimeout(() => {
  set(dataTreeSelectValue, [
    { id: '1', name: '1111' },
    { id: '2', name: '222' },
    { id: '3', name: '3333' },
    { id: '4', name: '444' }
  ]);
  const bba = gridOptions.forms.find((f) => f.field === 'bba');
  if (bba)
    bba.props!.options = [
      { value: 1, label: '男' },
      { value: 2, label: '女' },
      { value: 3, label: '未知' }
    ];
  const institutionId = gridOptions.forms.find((f) => f.field === 'institutionId');
  if (institutionId)
    institutionId.props!.treeData = [
      { id: '1', name: '1111' },
      { id: '2', name: '222' },
      { id: '3', name: '3333' },
      { id: '4', name: '444' }
    ] as any;
  // console.log(gridOptions.forms);
}, 1000 * 3);

// for (let i = 0; i < 40; i++) {
//   gridOptions.data.push({ id: 10200+i, name: 'TestA'+i, code: 'TA'+i, price: null, doseType: '', minPackUnit: '' })
// }

const gridEvents = {
  headerCellClick(params) {
    const { column } = params;
    console.log(`表头单元格点击${column.title}`);
    openExpand.value = true;
    const $grid = get(tablePlanRef);
    if ($grid) {
      $grid.updateData();
    }
  },
  headerCellDblclick(params) {
    const { column } = params;
    console.log(`表头单元格双击${column.title}`);
  },
  headerCellMenu(params) {
    const { column } = params;
    console.log(`表头右键单元格 ${column.title}`);
  },
  cellClick(params) {
    const { column } = params;
    console.log(`单元格点击${column.title}`);
    openExpand.value = false;
    const $grid = get(tablePlanRef);
    if ($grid) {
      $grid.updateData();
    }
  },
  cellDblclick(params) {
    const { column } = params;
    console.log(`单元格双击${column.title}`);
  },
  cellMenu(params) {
    const { row } = params;
    console.log(`单元格右键行 ${row.name}`);
  },
  footerCellClick(params) {
    const { column } = params;
    console.log(`表尾单元格点击${column.title}`);
  },
  footerCellDblclick(params) {
    const { column } = params;
    console.log(`表尾单元格双击${column.title}`);
  },
  footerCellMenu(params) {
    const { column } = params;
    console.log(`表尾右键单元格 ${column.title}`);
  },
  checkboxChange(params) {
    console.log(`复选框切换 ${params.checked}`);
  },
  checkboxAll(params) {
    console.log(`复选框全选切换 ${params.checked}`, params);
  },
  toolbarToolClick(code, tool) {
    console.log(`工具栏点击`, code, tool);
  },
  toolbarButtonClick(code, tool) {
    console.log(`工具栏点击`, code, tool);
  },
  formSearch(form) {
    console.log(`搜索条件`, form);
  },
  // scroll (params) {
  //   console.log(`滚动事件scrollTop=${params.scrollTop} scrollLeft=${params.scrollLeft}`)
  // },
  zoom(params) {
    console.log(`表格全屏 type=${params.type}`);
  },
  custom(params) {
    console.log(`表格自定义列 type=${params.type}`);
  }
};

const handleOpenTree = () => {
  useTrendsComp({
    type: 'modal',
    // type: "drawer",
    title: 'tree 详情',
    width: 'L',
    buttons: [
      {
        label: '确定1',
        type: 'primary',
        click: (data) => {
          console.log('确定1', data);
        }
      },
      {
        label: '取消2',
        type: 'default',
        click: (data) => {
          data.cancel();
          console.log('取消2', data);
        }
      },
      { label: '删除3', type: 'default', danger: true }
    ],
    component: tree,
    showButton: true,
    showClose: true,
    maskClosable: true
  }).show();
};

const handleOpenEdit = (type: string, item?: any) => {
  const {
    show: AAA,
    result,
    cancel
  } = useTrendsComp({
    type: 'modal',
    // type: 'drawer',
    // title: '测试标题' + type,
    width: 'L',
    height: 500,
    component: edit,
    param: { id: type === 'add' ? null : item?.name },
    showButton: true,
    showClose: true,
    maskClosable: true
  });
  AAA();
  watch(
    () => result.value,
    (data) => {
      console.log('watch:result', data);
      cancel();
    }
  );

  // setTimeout(() => {
  //   const { show: BBB } = useTrendsComp({
  //     type: 'modal',
  //     // type: 'drawer',
  //     // title: '测试标题' + type,
  //     width: "L",
  //     component: edit,
  //     param: { id: type === 'add' ? null : item?.name }
  //   });
  //   BBB().then(data => console.log(data));
  // }, 1000);
};
</script>
